﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using Trentacular.Office.Server.Search.FacetedSearch;
using Trentacular.Office.Server.Web.UI.WebParts;
using Trentacular.SharePoint.Web.UI;
using Trentacular.SharePoint.Web.UI.WebParts;

namespace Trentacular.Office.Server.Web.UI.UserControls
{
    public partial class FacetedSearchEditor : BaseSPUserControl, IWebPartEditor<FacetedSearchWebPart>
    {
        #region IWebPartEditor<FacetedSearchWebPart> Members

        public FacetedSearchWebPart WebPartToEdit { get; set; }

        public bool ApplyChanges()
        {
            int facetResultsRowLimit;
            if (int.TryParse(txtFacetResultsRowLimit.Text, out facetResultsRowLimit))
                WebPartToEdit.FacetResultsRowLimit = facetResultsRowLimit;

            WebPartToEdit.FacetProviderConfigurations = GetFacetProviderConfigurations();

            WebPartToEdit.EnableDebugPanel = cbxDebugPanel.Checked;

            return true;
        }

        public void SyncChanges()
        {
            txtFacetResultsRowLimit.Text = WebPartToEdit.FacetResultsRowLimit.ToString();
            txtFacetProvidersXml.Text = GetFacetProvidersXml();
            cbxDebugPanel.Checked = WebPartToEdit.EnableDebugPanel;
        }

        #endregion

        private string GetFacetProvidersXml()
        {
            var xmlOutput = new StringBuilder();
            var xmlWriter = XmlWriter.Create(xmlOutput, new XmlWriterSettings
            {
                Indent = true,
                OmitXmlDeclaration = true
            });

            var serializer = new DataContractSerializer(typeof(FacetProviderConfigurationCollection));
            serializer.WriteObject(xmlWriter, WebPartToEdit.FacetProviderConfigurations);
            xmlWriter.Flush();

            return xmlOutput.ToString();
        }

        private FacetProviderConfigurationCollection GetFacetProviderConfigurations()
        {
            using (var stringReader = new StringReader(txtFacetProvidersXml.Text))
            {
                var xmlReader = XmlReader.Create(stringReader);
                var serializer = new DataContractSerializer(typeof(FacetProviderConfigurationCollection));
                var facetProviderConfigurations = serializer.ReadObject(xmlReader) as FacetProviderConfigurationCollection;
                if (facetProviderConfigurations == null)
                    throw new ArgumentException("Invalid Facet Provider Configurations Xml");

                return facetProviderConfigurations;
            }
        }
    }
}